﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using KeyCore.Framework.DbInit;
using KeyCore.Loans.Client.Web.Models.LoansClient;

namespace KeyCore.Loans.Client.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            InitializeDatabase();
            AreaRegistration.RegisterAllAreas();

            //    WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.Add(typeof(ILoansClientWizardStep), new LoansClientStepViewModelBinder());
        }

        // create database if not exist with default user admin and 2 default roles 
        // do not run in  productiobn ???
        private void InitializeDatabase()
        {
            using (var dc = new KeyCoreDbContext())
            {
                //  if (!dc.Database.Exists())
                dc.Database.Initialize(true);
            }
        }
    }

    public class LoansClientStepViewModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var stepTypeValue = bindingContext.ValueProvider.GetValue("StepType");
            var stepType = Type.GetType((string)stepTypeValue.ConvertTo(typeof(string)), true);
            var step = Activator.CreateInstance(stepType);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => step, stepType);
            return step;
            //return base.CreateModel(controllerContext, bindingContext, modelType);
        }
    }

    //public class LoansClientStepViewModelBinder : IModelBinder
    //{
    //    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    //    {
    //        var stepTypeValue = bindingContext.ValueProvider.GetValue("StepType");
    //        var stepType = Type.GetType((string)stepTypeValue.ConvertTo(typeof(string)), true);
    //        var step = Activator.CreateInstance(stepType);
    //        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => step, stepType);
    //        //foreach (var result in ModelValidator.GetModelValidator(bindingContext.ModelMetadata,controllerContext).Validate(null))
    //        //{
    //        //    bindingContext.ModelState.AddModelError(result.MemberName,result.Message);
    //        //}
    //        return step;
    //    }
    //}
}
